﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VirtualPress.Infrastructure.Entities.Entity;
using VirtualPress.Infrastructure.Entities;
using VirtualPress.Infrastructure.Entities.Repository;
using VirtualPress.Infrastructure.Entities.Enum;
using System.Web;
using System.IO;
using VirtualPress.Engine.ExServer.WorkPool;
using VirtualPress.Engine.ExServer.WorkPool.WorkHandle.Email;
using VirtualPress.Tool.Configration;
using System.Linq.Expressions;
using VirtualPress.Tool.Framework;
using VirtualPress.Infrastructure.Entities.JSONModel;
using VirtualPress.Infrastructure.Entities.Cache;
using VirtualPress.Portal.Biz.Content;

namespace VirtualPress.Portal.Biz
{
    public class MeetingBiz
    {
        #region 会议管理
        public static List<Meeting> GetAllMeeting(int active, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                IQueryable<T_Meeting> query = null;
                if (active == 9)
                {
                    query = ctx.Meeting.Where(c => true);
                }
                else
                {
                    query = ctx.Meeting.Where(c => c.isActive == (active == 1));
                }
                return query.OrderByDescending(c => c.Id)
                        .Skip(page * pageSize)
                        .Take(pageSize)
                        .ToList()
                        .Select(c => new Meeting().Set(c))
                        .ToList();
            }
        }
        public static List<Meeting> GetAllMeeting(Expression<Func<T_Meeting, bool>> where, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.Meeting
                    .Where(where)
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new Meeting().Set(c))
                    .ToList();
                return list;
            }
        }
        public static int GetAllMeetingForPage(int active)
        {
            using (Context ctx = new Context())
            {
                IQueryable<T_Meeting> query = null;
                if (active == 9)
                {
                    query = ctx.Meeting.Where(c => true);
                }
                else
                {
                    query = ctx.Meeting.Where(c => c.isActive == (active == 1));
                }
                return query.Count();
            }
        }
        public static int GetAllMeetingForPage(Expression<Func<T_Meeting, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.Meeting.Count(where);
            }

        }
        public static bool NewMeeting(Meeting meeting)
        {
            if (new Meeting().Any(c => c.Name == meeting.Name))
            {
                return false;
            }
            var user = new User().Find(meeting.Admin);
            if (user != null)
            {
                return false;
            }
            var file = System.Web.HttpContext.Current.Request.Files["Logo"];
            if (file != null && file.ContentLength > 0)
            {
                string basedir = "/content/meeting/" + meeting.Name + "/coverimage/";
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                var fileinfo = new FileInfo(file.FileName);
                string filePath = basedir + meeting.Name + "-converimage" + fileinfo.Extension;
                file.SaveAs(HttpContext.Current.Server.MapPath(filePath));
                meeting.Logo = filePath;
            }
            UserBiz.Register(
                new User()
                {
                    Area = 0,
                    Birthday = DateTime.Parse("1980-01-01"),
                    Email = meeting.Admin,
                    Gender = Gender.Male,
                    IsActivate = true,
                    IsRefuse = false,
                    Location = 0,
                    NickName = meeting.Name + "管理员",
                    Password = "123456",
                    Photo = meeting.Logo,
                    Profession = 0,
                    RcdDate = DateTime.Now,
                    SystemRole = UserRole.ConferenceAdmin,
                    UserName = meeting.Admin
                }, true);

            meeting.DefaultExamineDay = 30;//默认审回时间为30天
            meeting.ManuscriptPageSize = SiteResource.DefaultPageSize;
            meeting.PagePrice = SiteResource.DefaultPagePrice;
            meeting.PricePerPrice = SiteResource.DefaultPricePerPage;
            meeting.PublicationPrice = SiteResource.DefaultPublicationPrice;
            meeting = meeting.PostAdd();

            new ConferenceMapping()
            {
                ConferenceId = meeting.Id,
                Host = meeting.ShortName + ".csaep.org"
            }.PostAdd();

            string toAdmin = EmailBuilder.BuildNewOrgIsCreateEmail(meeting.Name, OrganizationType.Meeting, meeting.Admin);
            if (!String.IsNullOrEmpty(toAdmin))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify, new NormalNotifyEmail()
                {
                    Message = toAdmin,
                    Recipient = meeting.Email,
                    Title = "会议 \"" + meeting.Name + "\" 已经创建"
                });
            }
            return true;
        }
        public static List<String> GetMeetingGroupName()
        {
            using (Context ctx = new Context())
            {
                var list = ctx.Meeting
                    .GroupBy(c => c.GroupName)
                    .Select(c => c.Key)
                    .ToList()
                    .Where(c=>!String.IsNullOrEmpty(c))
                    .ToList();
                return list;
            }
        }
        public static void EnableMeeting(int id)
        {
            string username = HttpContext.Current.User.Identity.Name;
            if (!String.IsNullOrEmpty(username))
            {
                if (new User().Find(username).SystemRole != UserRole.Admin)
                {
                    return;
                }
                var meeting = new Meeting().Find(id.ToString());
                if (meeting != null)
                {
                    meeting.isActive = true;
                    meeting.PostModify();
                }
            }
        }
        public static void DisableMeeting(int id)
        {
            string username = HttpContext.Current.User.Identity.Name;
            if (!String.IsNullOrEmpty(username))
            {
                if (new User().Find(username).SystemRole != UserRole.Admin)
                {
                    return;
                }
                var meeting = new Meeting().Find(id.ToString());
                if (meeting != null)
                {
                    meeting.isActive = false;
                    meeting.PostModify();
                }
            }
        }
        public static void DeleteMeeting(int id)
        {
            string username = HttpContext.Current.User.Identity.Name;
            if (!String.IsNullOrEmpty(username))
            {
                if (new User().Find(username).SystemRole != UserRole.Admin)
                {
                    return;
                }
                var meeting = new Meeting().Find(id.ToString());
                if (meeting != null)
                {
                    meeting.PostDelete();
                }
                var user = new User().Find(meeting.Admin);
                if (user != null)
                {
                    user.PostDelete();
                }
            }
        }
        public static void EditMeeting(Meeting meeting)
        {
            //var entity = new Meeting().Find(meeting.Id.ToString());
            if (meeting != null)
            {
                var file = System.Web.HttpContext.Current.Request.Files["Logo"];
                if (file != null && file.ContentLength > 0)
                {
                    string basedir = "/content/meeting/" + meeting.Name + "/coverimage/";
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                    }
                    var fileinfo = new FileInfo(file.FileName);
                    string filePath = basedir + meeting.Name + "-converimage" + fileinfo.Extension;
                    file.SaveAs(HttpContext.Current.Server.MapPath(filePath));
                    meeting.Logo = filePath;
                }
                meeting.PostModify();
            }

        }
        public static List<FriendLink> GetAllLinks(Expression<Func<T_FriendLink, bool>> where, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.FriendLink
                    .Where(where)
                    .OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new FriendLink().Set(c))
                    .ToList();
                return list;
            }
        }
        public static int GetAllLinksForPage(Expression<Func<T_FriendLink, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.FriendLink.Count(where);
            }
        }
        public static FriendLink SaveNewFriendLink(FriendLink entity)
        {
            if (entity != null)
            {
                return entity.PostAdd();
            }
            return null;
        }
        public static FriendLink GetLink(int Id)
        {
            return new FriendLink().Find(Id.ToString());
        }
        #endregion

        #region 稿件管理
        /// <summary>
        /// 稿件修订
        /// </summary>
        /// <param name="articleId"></param>
        public static void ArticleEdit(int articleId)
        {
            var article = new Article().Find(articleId.ToString());
            if (article == null || article.UserName != HttpContext.Current.User.Identity.Name ||
                !(article.Status == ArticleStatus.ZhuanShenXiuDing || article.Status == ArticleStatus.ZhongShenXiuDing))
            {
                return;
            }
            var meeting = new Meeting().Find(article.Conference_Id.ToString());
            string basedir = "/content/meeting/" + meeting.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
            var file = HttpContext.Current.Request.Files["Appendix"];
            string appendixPath = string.Empty;
            string appendixName = string.Empty;
            string appendixCode = string.Empty;
            string format = string.Empty;
            string size = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(article.Code, AttachmentStatus.XiuDingGao, article.Id);

                var fileInfo = new FileInfo(file.FileName);
                size = Math.Round(
                    decimal.Parse(file.ContentLength.ToString()) / 1024,
                    2).ToString() + " KB";
                string extendName = fileInfo.Extension;
                format = extendName.Replace(".", "").ToUpper();
                appendixName = fileInfo.Name.Replace(extendName, "");

                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                appendixPath = basedir + appendixCode + extendName;
            }
            if (!String.IsNullOrEmpty(appendixPath))
            {
                //创建新附件
                var attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Manuscript,
                    AppendixCode = appendixCode,
                    CreateTime = DateTime.Now,
                    FileName = appendixName,
                    Path = appendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id,
                    AttachmentStatus = AttachmentStatus.XiuDingGao,
                    Format = format,
                    Size = size
                };
                attachment.PostAdd();
            }
            if (article.Status == ArticleStatus.ZhuanShenXiuDing)
            {
                //创建历史记录
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhuanShenXiuDingWanCheng,
                    ManuscriptId = article.Id,
                    Message = "专审修订完成",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();
                article.Status = ArticleStatus.ZhuanShenXiuDingWanCheng;
                article.PostModify();
            }
            else if (article.Status == ArticleStatus.ZhongShenXiuDing)
            {
                //创建历史记录
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhongShenXiuDingWanCheng,
                    ManuscriptId = article.Id,
                    Message = "终审修订完成",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();
                article.Status = ArticleStatus.ZhongShenXiuDingWanCheng;
                article.PostModify();
            }
        }
        public static List<Article> GetAllArticle(Expression<Func<T_Article, bool>> where, bool loadexaminedetail, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.Article
                    .Where(where)
                    .Join(
                        ctx.Meeting,
                        m => m.Conference_Id,
                        p => p.Id,
                        (m, p) => new { m, p })
                    .Join(
                        ctx.ArticleAuthor,
                        c => c.m.Id,
                        a => a.ManuscriptId,
                        (c, a) => new { c, a })
                    .GroupBy(c => c.c.m.Id)
                    .OrderByDescending(c => c.Key)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new Article().Set(c.FirstOrDefault().c.m)
                    .LoadMeeting(new Meeting().Set(c.FirstOrDefault().c.p))
                    .LoadArticleAuthor(c.Select(o => new ArticleAuthor().Set(o.a)).ToList()))
                    .ToList();
                if (loadexaminedetail)
                {
                    var keys = list.Select(m => m.Id).ToList();
                    var records = ctx.AuditingRecord.Where(c =>
                        keys.Contains(c.ManuscriptId) && c.Step == (int)ExamineStep.ZhuanShen)
                        .GroupBy(c => c.ManuscriptId)
                        .ToList();
                    foreach (var article in list)
                    {
                        var item = records.FirstOrDefault(c => c.Key == article.Id);
                        article.ExamineTotle = item.Count(c => c.ExamineStatus == (int)ExamineStatus.DaiShenHe || c.ExamineStatus == (int)ExamineStatus.WanCheng);
                        article.ExamineComplete = item.Count(c => c.ExamineStatus == (int)ExamineStatus.WanCheng);
                    }
                }

                return list;
            }
        }
        public static int GetAllArticleForPage(Expression<Func<T_Article, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.Article.Count(where);
            }
        }
        /// <summary>
        /// 会议投稿
        /// </summary>
        /// <param name="article"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static bool Contribute(Article article, List<string> authorlist)
        {
            var meeting = new Meeting().Find(article.Conference_Id.ToString());

            article.Code = new StreamFactory().BuildArticleStreamNo(meeting.ShortName, BuildStreamType.Manuscript, meeting.Id);
            //创建稿件
            article.PostAdd();

            if (article == null)
            {
                LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "会议投稿保存稿件失败。" + Environment.NewLine + article.ToJson());
                return false;
            }
            var file = HttpContext.Current.Request.Files["Appendix"];
            Appendix attachment = null;
            string basedir = "/content/meeting/" + meeting.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
            string appendixPath = string.Empty;
            string appendixCode = string.Empty;
            string format = string.Empty;
            string size = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(article.Code, AttachmentStatus.ChuGao, article.Id);
                var fileInfo = new FileInfo(file.FileName);
                size = Math.Round(
                    decimal.Parse(file.ContentLength.ToString()) / 1024,
                    2).ToString() + " KB";
                string extendName = fileInfo.Extension;
                format = extendName.Replace(".", "").ToUpper();
                string fileName = fileInfo.Name.Replace(extendName, "");
                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                appendixPath = basedir + appendixCode + extendName;

                //创建附件
                attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Manuscript,
                    AppendixCode = appendixCode,
                    CreateTime = DateTime.Now,
                    FileName = fileName,
                    Path = appendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id,
                    AttachmentStatus = AttachmentStatus.ChuGao,
                    Format = format,
                    Size = size
                };
                attachment.PostAdd();
                if (attachment == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "会议投稿保存稿件附件失败，请手工处理" + Environment.NewLine + attachment.ToJson());
                }
            }

            var recommendation = HttpContext.Current.Request.Files["Recommendation"];
            string recommendationAppendixPath = string.Empty;

            if (attachment != null && recommendation != null && recommendation.ContentLength > 0)
            {
                var fileInfo = new FileInfo(recommendation.FileName);
                string extendName = fileInfo.Extension;
                string fileName = fileInfo.Name.Replace(extendName, "");
                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + attachment.AppendixCode + "-recommand" + extendName));
                recommendationAppendixPath = basedir + attachment.AppendixCode + "-recommand" + extendName;

                //创建附件
                var recommand = new Appendix()
                {
                    AttachmentType = AttachmentType.Recommendation,
                    AppendixCode = attachment.AppendixCode + "-recommand",
                    CreateTime = DateTime.Now,
                    FileName = fileName,
                    Path = recommendationAppendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id
                };
                recommand.PostAdd();
                if (recommand == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件推荐书失败，请手工处理" + Environment.NewLine + attachment.ToJson());
                }
            }

            //创建稿件历史
            new ArticleHistory()
            {
                CreateTime = DateTime.Now,
                CurrentStatus = ArticleStatus.Open,
                Message = "投稿成功",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = ArticleStatus.Open,
                ManuscriptId = article.Id
            }.PostAdd();


            //创建审稿记录
            new AuditingRecord()
            {
                CreateTime = DateTime.Now,
                Distributor = "system",
                ExamineStatus = ExamineStatus.DaiShenHe,
                MeetingId = article.Conference_Id,
                LastRecord = DateTime.Now,
                ManuscriptId = article.Id,
                Step = ExamineStep.ChuShen,
                UserName = meeting.Admin,
                SuggestStatus = 0
            }.PostAdd();

            //创建期刊作者
            foreach (var item in authorlist)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    var writer = new Author().Find(item);
                    if (writer != null)
                    {
                        var author = new ArticleAuthor()
                        {
                            AuthorId = writer.Id,
                            AuthorName = writer.LastName + writer.FirstName,
                            ManuscriptId = article.Id
                        }.PostAdd();
                        if (author == null)
                        {
                            LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件作者失败，请手工处理" + Environment.NewLine + author.ToJson());
                        }
                    }
                }
            }
            string toAuthor = EmailBuilder.BuildContributeEmail(article.Id);
            if (!String.IsNullOrEmpty(toAuthor))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                new NormalNotifyEmail()
                {
                    Message = toAuthor,
                    Title = String.Format("{0} 投稿成功", article.Title),
                    Recipient = article.UserName
                });
            }

            string toOrg = EmailBuilder.BuildNewArticleIncomeEmail(article.Id, OrganizationType.Meeting, meeting.Id);
            if (!String.IsNullOrEmpty(toOrg))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                    new NormalNotifyEmail()
                    {
                        //BackUrl = "/workspace/console/article?type=0",
                        Message = toOrg,
                        Title = "您的会议收到一封新稿件",
                        Recipient = meeting.Email
                    });
            }
            return true;
        }
        public static void CancelArticle(int id)
        {
            var article = new Article().Find(c => c.Id == id && c.UserName == System.Web.HttpContext.Current.User.Identity.Name && c.ArticleType == (int)ArticleType.Meeting && !c.IsDelete && (c.Status == 0 || c.Status == 99));
            if (article != null)
            {
                article.IsDelete = true;
                article.PostModify();
                //创建稿件历史
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = article.Status,
                    ManuscriptId = article.Id,
                    Message = "删除稿件",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();
            }
        }
        public static List<ArticleHistory> GetAllArticleHistory(int articleId)
        {
            using (Context ctx = new Context())
            {
                return ctx.ArticleHistory
                    .Where(c => c.ManuscriptId == articleId)
                    .ToList()
                    .Select(c => new ArticleHistory().Set(c))
                    .ToList();
            }
        }
        public static List<AuditingRecord> GetAllAuditingRecord(int articleId)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.AuditingRecord
                            where c.ManuscriptId == articleId
                            join m in ctx.User
                            on c.UserName equals m.UserName
                            select new { c, m.NickName })
                           .ToList()
                           .Select(c =>
                           {
                               var item = new AuditingRecord().Set(c.c);
                               item.ExpertRealName = c.NickName;
                               return item;
                           })
                           .ToList();
                return data;
            }
        }
        public static bool ArticleEdit(Article article, List<string> authorList)
        {
            var meeting = new Meeting().Find(article.Conference_Id.ToString());
            string basedir = "/content/meeting/" + meeting.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
            var file = HttpContext.Current.Request.Files["Appendix"];
            string appendixPath = string.Empty;
            string appendixCode = string.Empty;
            string appendixName = string.Empty;
            string format = string.Empty;
            string size = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(article.Code, AttachmentStatus.ChuGao, article.Id);
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }

                var fileInfo = new FileInfo(file.FileName);
                size = Math.Round(
                    decimal.Parse(file.ContentLength.ToString()) / 1024,
                    2).ToString() + " KB";
                string extendName = fileInfo.Extension;
                format = extendName.Replace(".", "").ToUpper();
                appendixName = fileInfo.Name.Replace(extendName, "");
                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                appendixPath = basedir + appendixCode + extendName;
            }
            if (!String.IsNullOrEmpty(appendixPath))
            {
                //删除原有附件
                var attachment = new Appendix().Find(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(attachment.Path)))
                {
                    try
                    {
                        System.IO.File.Delete(HttpContext.Current.Server.MapPath(attachment.Path));
                    }
                    catch (Exception e)
                    {
                        LogHelper.Write(CommonLogger.Journal, LogLevel.Error, e);
                    }
                }
                //删除原附件
                attachment.PostDelete();
                //创建新附件
                attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Manuscript,
                    AppendixCode = appendixCode,
                    CreateTime = DateTime.Now,
                    FileName = appendixName,
                    Path = appendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id,
                    AttachmentStatus = AttachmentStatus.ChuGao,
                    Format = format,
                    Size = size
                };
                attachment.PostAdd();
            }

            var recommendation = HttpContext.Current.Request.Files["Recommendation"];
            string recommendationAppendixPath = string.Empty;
            string recommendationAppendixName = string.Empty;
            if (recommendation != null && recommendation.ContentLength > 0)
            {
                var fileInfo = new FileInfo(recommendation.FileName);
                string extendName = fileInfo.Extension;
                recommendationAppendixName = fileInfo.Name.Replace(extendName, "");

                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + "-recommand" + extendName));
                recommendationAppendixPath = basedir + appendixCode + "-recommand" + extendName;
            }
            if (!String.IsNullOrEmpty(recommendationAppendixPath))
            {
                //删除原有推荐材料
                var attachment = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(attachment.Path)))
                {
                    try
                    {
                        System.IO.File.Delete(HttpContext.Current.Server.MapPath(attachment.Path));
                    }
                    catch (Exception e)
                    {
                        LogHelper.Write(CommonLogger.Journal, LogLevel.Error, e);
                    }
                }
                //删除原推荐材料
                attachment.PostDelete();
                //创建新推荐材料
                attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Recommendation,
                    AppendixCode = appendixCode + "-recommand",
                    CreateTime = DateTime.Now,
                    FileName = recommendationAppendixName,
                    Path = recommendationAppendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id
                };
                attachment.PostAdd();
            }


            //创建稿件历史
            var history = new ArticleHistory()
            {
                ManuscriptId = article.Id,
                CreateTime = DateTime.Now,
                CurrentStatus = article.Status,
                Message = "修订稿件",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = article.Status
            };
            history.PostAdd();

            //删除员稿件作者成员记录
            var articleAuthor = new ArticleAuthor().FindAll(c => c.ManuscriptId == article.Id);
            if (authorList != null && authorList.Any())
            {
                articleAuthor.ForEach(c => c.PostDelete());
            }
            //创建期刊作者
            foreach (var item in authorList)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    var writer = new Author().Find(item);
                    if (writer != null)
                    {
                        var author = new ArticleAuthor()
                        {
                            AuthorId = writer.Id,
                            AuthorName = writer.LastName + " " + writer.FirstName,
                            ManuscriptId = article.Id
                        }.PostAdd();
                        if (author == null)
                        {
                            LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件作者失败，请手工处理" + Environment.NewLine + author.ToJson());
                        }
                    }
                }
            }

            return article.PostModify() != null;
        }
        /// <summary>
        /// 终审验收
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="result"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool ConclusiveExamine(int articleId, int totalPay, int result, string msg)
        {
            var user = new User().Find(HttpContext.Current.User.Identity.Name);
            var article = new Article().Find(articleId.ToString());
            if (user == null || article == null)
            {
                return false;
            }
            var meeting = new Meeting().Find(article.Conference_Id.ToString());
            if (meeting == null || !(meeting.Admin.ToLower() == HttpContext.Current.User.Identity.Name.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return false;
            }
            if (result == 0)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhongShenWanCheng,
                    ManuscriptId = article.Id,
                    Message = "终审通过",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                var record = new AuditingRecord().Find(c => c.ManuscriptId == article.Id && c.Step == 3 && c.ExamineStatus == 1);

                if (record != null)
                {
                    record.ExamineStatus = ExamineStatus.WanCheng;
                    record.LastRecord = DateTime.Now;
                    record.PostModify();
                }

                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.LuYong,
                    ManuscriptId = article.Id,
                    Message = "录用",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.LuYong;
                article.PostModify();

                var bill = new Reckoning()
                {
                    CreateTime = DateTime.Now,
                    Message = String.Format("期刊《{0}》出版费用", article.Title),
                    Own = article.UserName,
                    PayFor = 0,
                    RaletionId = article.Id,
                    Status = 0,
                    TotalPay = totalPay
                }.PostAdd();
                if (bill == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error,
                        "稿件" + article.Id + "记录代缴费记录失败，请人工处理");
                }

                string toAuthor = EmailBuilder.BuildAcceptanceNotityEmail(article.Id, totalPay, OrganizationType.Meeting);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                       new NormalNotifyEmail()
                       {
                           Recipient = article.UserName,
                           Title = "您的稿件已被录用",
                           Message = toAuthor
                       });
                }
                //WorkPool.Append<PublicationEmail>(WorkType.email_for_publication,
                //   new PublicationEmail()
                //   {
                //       ArticleName = article.Title,
                //       Recipient = article.UserName,
                //       Message = String.Format("您的稿件《{0}》已终审通过且被录用，现需要您支付{1}元的版面费，在您缴费以后期刊方将为您安排出版。如有疑问请与期刊方联系。",
                //       article.Title, totalPay),
                //       BackUrl = "/workspace/member/bill"
                //   });

                //WorkPool.Append<PublicationEmail>(WorkType.email_for_publication,
                //   new PublicationEmail()
                //   {
                //       ArticleName = article.Title,
                //       Recipient = article.UserName,
                //       Message = String.Format("您的稿件《{0}》已终审通过且被录用，现需要您支付{1}元的版面费，在您缴费以后期刊方将为您安排出版。如有疑问请与期刊方联系。",
                //       article.Title, totalPay),
                //       BackUrl = "/workspace/member/bill"
                //   });
            }
            else if (result == 1)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhongShenXiuDing,
                    ManuscriptId = article.Id,
                    Message = "终审修订",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.ZhongShenXiuDing;
                article.PostModify();

                var att = new Appendix().FindLast(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
                att.Suggestion = msg;
                att.PostModify();

                //给作者发邮件
                string toAuthor = EmailBuilder.BuildRevisionForAuthorEmail(article.Id, OrganizationType.Meeting, msg);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件需要修订",
                            Message = toAuthor
                        });
                }
                //WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                //    new NormalNotifyEmail()
                //    {
                //        Recipient = article.UserName,
                //        Title = "您的稿件终审完成，需要修订",
                //        Message = String.Format("您的稿件《{0}》已通过管理员终审验收但需要您进行终审修订。<br/>{1}", article.Title, msg)
                //    });
            }
            else if (result == 9)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.Close,
                    ManuscriptId = article.Id,
                    Message = "终审不通过",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.Close;
                article.PostModify();

                var att = new Appendix().FindLast(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
                att.Suggestion = msg;
                att.PostModify();

                //给作者发邮件
                string toAuthor = EmailBuilder.BuildZhongShenRefuseEmail(
                     article.Title, msg);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件终审不通过",
                            Message = toAuthor
                        });
                }
            }
            return true;
        }
        public static bool ManualArticle(Article article, List<string> authorlist)
        {
            var meeting = new Meeting().Find(article.Conference_Id.ToString());
            if(meeting == null){
                return false;
            }
            //创建稿件
            article.PostAdd();
            if (article == null)
            {
                LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件失败。" + Environment.NewLine + article.ToJson());
                return false;
            }
            article.Code = new StreamFactory().BuildArticleStreamNo(meeting.ShortName, BuildStreamType.Manuscript, meeting.Id);
            article.PostModify();

            var file = HttpContext.Current.Request.Files["Appendix"];
            string appendixPath = string.Empty;
            string appendixCode = string.Empty;
            string appendixName = string.Empty;
            string format = string.Empty;
            string size = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(
                    article.Code, AttachmentStatus.DingGao, article.Id);
                string basedir = "/content/meeting/" + meeting.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                {
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                }
                size = Math.Round(
                     decimal.Parse(file.ContentLength.ToString()) / 1024,
                     2).ToString() + " KB";
                var fileInfo = new FileInfo(file.FileName);
                string extendName = fileInfo.Extension;
                format = extendName.Replace(".", "").ToUpper();
                appendixName = fileInfo.Name.Replace(extendName, "");

                file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                appendixPath = basedir + appendixCode + extendName;

                //创建附件
                var attachment = new Appendix()
                {
                    AttachmentType = AttachmentType.Manuscript,
                    AppendixCode = appendixCode,
                    CreateTime = DateTime.Now,
                    FileName = appendixName,
                    Path = appendixPath,
                    Own = HttpContext.Current.User.Identity.Name,
                    RaletionId = article.Id,
                    AttachmentStatus = AttachmentStatus.DingGao,
                    Format=format,
                    Size=size
                };
                attachment.PostAdd();
                if (attachment == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件附件失败，请手工处理" + Environment.NewLine + attachment.ToJson());
                }
            }
            //创建稿件历史
            var history = new ArticleHistory()
            {
                CreateTime = DateTime.Now,
                CurrentStatus = ArticleStatus.ChuBanYiJiaoFei,
                Message = "管理员手工维护",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = ArticleStatus.Open
            };
            history.ManuscriptId = article.Id;
            history.PostAdd();
            //创建期刊作者
            foreach (var item in authorlist)
            {
                if (!String.IsNullOrEmpty(item))
                {
                    var writer = new Author().Find(item);
                    if (writer != null)
                    {
                        var author = new ArticleAuthor()
                        {
                            AuthorId = writer.Id,
                            AuthorName = writer.LastName + writer.FirstName,
                            ManuscriptId = article.Id
                        }.PostAdd();
                        if (author == null)
                        {
                            LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "投稿保存稿件作者失败，请手工处理" + Environment.NewLine + author.ToJson());
                        }
                    }
                }
            }
            return true;
        }
        #endregion

        #region 审稿
        /// <summary>
        /// 为稿件查询可参与审稿的专家
        /// </summary>
        /// <param name="meeting"></param>
        /// <param name="article"></param>
        /// <returns></returns>
        public static List<ExpertAndJobModel> FindExpertForExamine(Meeting meeting, Article article, List<string> except)
        {
            using (Context ctx = new Context())
            {
                except = except == null ? new List<string>() : except;
                var leager = (from c in ctx.Organization
                              join e in ctx.Expert
                                 on c.UserName equals e.UserName
                              join u in ctx.User
                                 on c.UserName equals u.UserName
                              where c.ApplyStatus == 1 && c.OrgId == meeting.Id && c.Status == 2 //&& !except.Contains(c.UserName)
                              select new
                              {
                                  ExperUserName = c.UserName,
                                  ExpertName = u.NickName,
                                  JobCount = ctx.AuditingRecord.Count(i => new List<int>() { 1, 2 }.Contains(i.ExamineStatus) && i.UserName == c.UserName)
                              }).ToList()
                             .Select(c => new ExpertAndJobModel()
                             {
                                 ExpertName = "B " + c.ExpertName,
                                 ExpertUserName = c.ExperUserName,
                                 JobCount = c.JobCount
                             })
                             .ToList();
                var employ = (from c in ctx.Expert
                              join u in ctx.User
                                 on c.UserName equals u.UserName
                              where c.Profession == (int)meeting.IndType
                              select new
                              {
                                  ExperUserName = c.UserName,
                                  ExpertName = "Z " + u.NickName,
                                  JobCount = ctx.AuditingRecord.Count(i => new List<int>() { 1, 2 }.Contains(i.ExamineStatus) && i.UserName == c.UserName)
                              }).ToList()
                               .Select(c => new ExpertAndJobModel()
                               {
                                   ExpertName = c.ExpertName,
                                   ExpertUserName = c.ExperUserName,
                                   JobCount = c.JobCount
                               })
                               .ToList();

                List<ExpertAndJobModel> Res = new List<ExpertAndJobModel>();
                var list = leager.Union(employ);
                foreach (var item in list)
                {
                    if (!Res.Any(c => c.ExpertUserName == item.ExpertUserName))
                    {
                        Res.Add(item);
                    }
                }
                return Res;
            }
        }
        //初审
        public static bool DoManuscriptCheck(Article article, int Page, bool optionsRadios, string RefuseMessage)
        {
            Meeting meeting = new Meeting().Find(article.Conference_Id.ToString());
            if (article != null && meeting != null)
            {
                if (optionsRadios)
                {
                    var record = new AuditingRecord().Find(
                        c => c.Step == 1 && c.ExamineStatus == 1 && c.ManuscriptId == article.Id);
                    if (record != null)
                    {
                        record.ExamineStatus = ExamineStatus.WanCheng;
                        record.Message = "初审通过";
                        record.PostModify();
                    }

                    var recommendation = new Appendix().Find(c => c.Type == (int)AttachmentType.Recommendation && c.RaletionId == article.Id);
                    if (recommendation != null)
                    {
                        new ArticleHistory()
                        {
                            CreateTime = DateTime.Now,
                            CurrentStatus = ArticleStatus.ZhongShen,
                            ManuscriptId = article.Id,
                            Message = "专家推荐 - 进入终审",
                            Operator = HttpContext.Current.User.Identity.Name,
                            PreStatus = article.Status
                        }.PostAdd();
                        article.PageSize = Page;
                        article.Status = ArticleStatus.ZhongShen;
                        article.PostModify();
                        string toAuthor = EmailBuilder.BuildAcceptArticleWithCommandSheetEmail(article.Title, article.UserName);
                        if (!String.IsNullOrEmpty(toAuthor))
                        {
                            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                            new NormalNotifyEmail()
                            {
                                //BackUrl = "/workspace/console/article?type=0",
                                Message = toAuthor,
                                Title = "稿件《" + article.Title + "》初审完成",
                                Recipient = meeting.Email
                            });
                        }
                        //WorkPool.Append<ManuscriptCheckEmail>(WorkType.email_for_manuscriptcheck,
                        //   new ManuscriptCheckEmail()
                        //   {
                        //       ArticleName = article.Title,
                        //       Recipient = article.UserName,
                        //       Message = String.Format("您的稿件《{0}》初审通过，由于您提供了专家推荐材料，已经进入终审阶段。如有疑问请与期刊方联系。",
                        //       article.Title),
                        //       BackUrl = string.Empty
                        //   });
                    }
                    else
                    {
                        new ArticleHistory()
                        {
                            CreateTime = DateTime.Now,
                            CurrentStatus = ArticleStatus.ZhuanShenDaiJiaoFei,
                            ManuscriptId = article.Id,
                            Message = "初审通过",
                            Operator = HttpContext.Current.User.Identity.Name,
                            PreStatus = article.Status
                        }.PostAdd();
                        if (meeting.isFeeForExpertExmaine)
                        {
                            article.Status = ArticleStatus.ZhuanShenDaiJiaoFei;
                        }
                        else
                        {
                            new ArticleHistory()
                            {
                                CreateTime = DateTime.Now,
                                CurrentStatus = ArticleStatus.ZhuanShenDaiFenPei,
                                ManuscriptId = article.Id,
                                Message = "免专审费",
                                Operator = HttpContext.Current.User.Identity.Name,
                                PreStatus = ArticleStatus.ZhuanShenDaiJiaoFei
                            }.PostAdd();
                            article.Status = ArticleStatus.ZhuanShenDaiFenPei;
                        }
                        article.PageSize = Page;
                        article.PostModify();
                        if (meeting.isFeeForExpertExmaine)
                        {
                            int totalPay = meeting.ManuscriptPageSize >= Page ? meeting.PagePrice : (Page - meeting.ManuscriptPageSize) * meeting.PricePerPrice + meeting.PagePrice;

                            var bill = new Reckoning()
                            {
                                CreateTime = DateTime.Now,
                                Message = String.Format("期刊《{0}》专审费用", article.Title),
                                Own = article.UserName,
                                PayFor = 0,
                                RaletionId = article.Id,
                                Status = 0,
                                TotalPay = totalPay
                            }.PostAdd();
                            if (bill == null)
                            {
                                LogHelper.Write(CommonLogger.Journal, LogLevel.Error,
                                    "稿件" + article.Id + "记录代缴费记录失败，请人工处理");
                            }
                        }
                        string toAuthor = EmailBuilder.BuildFirstExaminationEmail(article.Title, article.UserName, meeting.isFeeForExpertExmaine);
                        if (!String.IsNullOrEmpty(toAuthor))
                        {
                            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                            new NormalNotifyEmail()
                            {
                                //BackUrl = "/workspace/console/article?type=0",
                                Message = toAuthor,
                                Title = "稿件《" + article.Title + "》初审完成",
                                Recipient = meeting.Email
                            });
                        }
                        //WorkPool.Append<ManuscriptCheckEmail>(WorkType.email_for_manuscriptcheck,
                        //   new ManuscriptCheckEmail()
                        //   {
                        //       ArticleName = article.Title,
                        //       Recipient = article.UserName,
                        //       Message = String.Format("您的稿件《{0}》初审通过，请尽快缴费以进行专审。：<br/>您的稿件一共{1}页，共需缴费：人民币 {2}元，如有疑问请与期刊方联系。",
                        //       article.Title, Page, totalPay),
                        //       BackUrl = "/workspace/member/bill"
                        //   });
                    }
                }
                else
                {
                    new ArticleHistory()
                    {
                        CreateTime = DateTime.Now,
                        CurrentStatus = ArticleStatus.Close,
                        ManuscriptId = article.Id,
                        Message = "初审不通过",
                        Operator = HttpContext.Current.User.Identity.Name,
                        PreStatus = article.Status
                    }.PostAdd();
                    article.Status = ArticleStatus.Close;
                    article.PostModify();

                    new AuditingRecord()
                    {
                        CreateTime = DateTime.Now,
                        Distributor = HttpContext.Current.User.Identity.Name,
                        ExamineStatus = ExamineStatus.QuXiao,
                        MeetingId = meeting.Id,
                        ManuscriptId = article.Id,
                        Message = "初审不通过",
                        Step = ExamineStep.ChuShen,
                        UserName = HttpContext.Current.User.Identity.Name
                    }.PostAdd();

                    var attachment = new Appendix().Find(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
                    if (attachment != null)
                    {
                        attachment.Suggestion = RefuseMessage;
                        attachment.PostModify();
                    }
                    string toAuthor = EmailBuilder.BuildFirstExaminationNotPassEmail(article.Title,
                        article.UserName, RefuseMessage);
                    if (!String.IsNullOrEmpty(toAuthor))
                    {
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Message = toAuthor,
                            Title = "您的稿件《"+article.Title+"》初审未通过",
                            Recipient = meeting.Email
                        });
                    }
                    //WorkPool.Append<ManuscriptCheckEmail>(WorkType.email_for_manuscriptcheck,
                    //    new ManuscriptCheckEmail()
                    //    {
                    //        ArticleName = article.Title,
                    //        Recipient = article.UserName,
                    //        Message = String.Format("您的稿件《{0}》初审未通过，初审意见为：<br/>{1}", article.Title, RefuseMessage)
                    //    });
                }
            }
            return false;
        }
        public static void CancelArticleForMeeting(int id)
        {
            string userName = HttpContext.Current.User.Identity.Name;
            var user = new User().Find(userName);
            if (String.IsNullOrEmpty(userName) || user == null)
            {
                return;
            }

            var article = new Article().Find(c => c.Id == id && !c.IsDelete);
            if (article == null)
            {
                return;
            }

            var meeting = new Meeting().Find(c => c.Id == article.Conference_Id);
            if (meeting == null || !(meeting.Admin.ToLower() == userName.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return;
            }
            article.IsDelete = true;
            article.PostModify();

            //创建稿件历史
            new ArticleHistory()
            {
                CreateTime = DateTime.Now,
                CurrentStatus = article.Status,
                ManuscriptId = article.Id,
                Message = "期刊管理员删除稿件",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = article.Status
            }.PostAdd();
        }
        /// <summary>
        /// 稿件分配
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="experts"></param>
        public static void DoDistribution(int articleId, DateTime finishDate, string expert)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated &&
                !String.IsNullOrEmpty(expert) && !String.IsNullOrEmpty(expert))
            {
                var user = new User().Find(HttpContext.Current.User.Identity.Name);
                if (user.SystemRole == UserRole.Admin || user.SystemRole == UserRole.ConferenceAdmin)
                {
                    var article = new Article().Find(articleId.ToString());
                    if (article != null)
                    {
                        var meeting = new Meeting().Find(article.Conference_Id.ToString());
                        if (meeting.Admin.ToLower() == HttpContext.Current.User.Identity.Name.ToLower() ||
                            user.SystemRole == UserRole.Admin)
                        {
                            switch (article.Status)
                            {
                                //专审待分配                                
                                case ArticleStatus.ZhuanShenDaiFenPei:
                                    string[] experts = expert.Split(';');
                                    List<Expert> prof = new List<Expert>();
                                    foreach (var item in experts)
                                    {
                                        if (String.IsNullOrEmpty(item))
                                        {
                                            continue;
                                        }
                                        var spcl = new Expert().Find(item);
                                        if (spcl == null)
                                        {
                                            continue;
                                        }
                                        prof.Add(spcl);
                                    }

                                    foreach (var item in prof)
                                    {
                                        var auditingRecord = new AuditingRecord()
                                        {
                                            CreateTime = DateTime.Now,
                                            Distributor = HttpContext.Current.User.Identity.Name,
                                            ExamineStatus = ExamineStatus.DaiShenHe,
                                            MeetingId = meeting.Id,
                                            ManuscriptId = article.Id,
                                            Step = ExamineStep.ZhuanShen,
                                            UserName = item.UserName,
                                            ExamineFinishDate = finishDate
                                        }.PostAdd();
                                        
                                        //给专家发邮件
                                        string toExpert = EmailBuilder.BuildReviewNotityEmail(article.Id,
                                            auditingRecord.Id, item.UserName, OrganizationType.Meeting, finishDate.ToString("yyyy-MM-dd"));
                                        if (!String.IsNullOrEmpty(toExpert))
                                        {
                                            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                                                new NormalNotifyEmail()
                                                {
                                                    Recipient = item.UserName,
                                                    Title = "专审邀请--《"+meeting.Name+"》",
                                                    Message = toExpert
                                                });
                                        }
                                        //WorkPool.Append<ZhuanShenJobEmail>(WorkType.email_for_examinejobdistribution,
                                        //    new ZhuanShenJobEmail()
                                        //    {
                                        //        BackUrl = "/home/receivepostdata?token=" +
                                        //        EncodeByBase64.Encode(AesAlgorithm.Encrypt(new ExamineTokenModel()
                                        //        {
                                        //            ExamineId = auditingRecord.Id,
                                        //            ArticleId = article.Id,
                                        //            expertUsername = item.UserName
                                        //        }.ToJson())),
                                        //        //ExamineSheetPath = HttpContext.Current.Server.MapPath(journal.ExamineSheet),
                                        //        JournalName = meeting.Name,
                                        //        ManuscriptPath = HttpContext.Current.Server.MapPath(new Appendix().FindLast(c => c.RaletionId == article.Id && c.Type == (int)AttachmentType.Manuscript).Path),
                                        //        ExamineFinishDate = finishDate,
                                        //        Recipient = item.UserName
                                        //    });
                                    }
                                    if (prof.Any())
                                    {
                                        new ArticleHistory()
                                        {
                                            CreateTime = DateTime.Now,
                                            CurrentStatus = ArticleStatus.ZhuanShen,
                                            ManuscriptId = article.Id,
                                            Message = "专审中",
                                            Operator = HttpContext.Current.User.Identity.Name,
                                            PreStatus = article.Status
                                        }.PostAdd();

                                        article.Status = ArticleStatus.ZhuanShen;
                                        article.PostModify();
                                    }
                                    break;
                                //专审完成，等待分配
                                case ArticleStatus.ZhuanShenWanCheng:
                                    break;
                                //专审修订完成，等待确认
                                case ArticleStatus.ZhuanShenXiuDingWanCheng:
                                    break;
                                //终审完成，等待分配
                                case ArticleStatus.ZhongShenWanCheng:
                                    break;
                                //终审修订完成，等待分配
                                case ArticleStatus.ZhongShenXiuDingWanCheng:
                                    break;
                            }
                        }
                    }
                }
            }
        }
        public static List<AuditingRecord> GetAllAuditingRecord(int articleId, Expression<Func<T_AuditingRecord, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var data = ctx.AuditingRecord
                    .Where(c => c.ManuscriptId == articleId)
                    .Where(where)
                    .Join(ctx.User,
                    e => e.UserName,
                    m => m.UserName,
                    (e, m) => new { e, m.NickName })
                    .ToList()
                    .Select(c =>
                    {
                        var item = new AuditingRecord().Set(c.e);
                        item.ExpertRealName = c.NickName;
                        return item;
                    })
                    .ToList();
                return data;
            }
        }
        public static void CancelExamineForArticle(int examineRecordId)
        {
            string userName = HttpContext.Current.User.Identity.Name;
            var user = new User().Find(userName);
            if (String.IsNullOrEmpty(userName) || user == null)
            {
                return;
            }

            var record = new AuditingRecord().Find(examineRecordId.ToString());
            if (record == null)
            {
                return;
            }

            var meeting = new Meeting().Find(c => c.Id == record.MeetingId);
            if (meeting == null || !(meeting.Admin.ToLower() == userName.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return;
            }

            record.ExamineStatus = ExamineStatus.QuXiao;
            record.Message = "管理员取消审核";
            record.PostModify();

            var article = new Article().Find(record.ManuscriptId.ToString());
            //给专家发邮件
            string toExpert = EmailBuilder.BuildCacnelExamineEmail(
                meeting.Name, OrganizationType.Meeting, article.Title);
            if (!String.IsNullOrEmpty(toExpert))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                  new NormalNotifyEmail()
                  {
                      Recipient = record.UserName,
                      Title = "管理员取消您的一项专审任务",
                      Message = toExpert
                  });
            }
            //WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
            //    new NormalNotifyEmail()
            //    {
            //        Recipient = record.UserName,
            //        Title = "管理员取消您的一项专审任务",
            //        Message = String.Format("《{0}》管理员取消您对于稿件《{1}》的专审任务。如有疑问请尽快与期刊方联系。", meeting.Name, article.Title)
            //    });
        }
        public static void urgeExamine(int auditingRecordId)
        {
            var auditingRecord = new AuditingRecord().Find(auditingRecordId.ToString());
            if (auditingRecord == null)
            {
                return;
            }
            var article = new Article().Find(auditingRecord.ManuscriptId.ToString());
            if (article == null)
            {
                return;
            }
            var meeting = new Meeting().Find(article.Conference_Id.ToString());
            if (meeting == null)
            {
                return;
            }
            //给专家发催审邮件
            string toExpert = EmailBuilder.BuildUrgeExamineEmail(article.Id, auditingRecord.Id,
                 OrganizationType.Meeting, auditingRecord.UserName);
            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                new NormalNotifyEmail()
                {
                    //BackUrl = "/workspace/console/article?type=0",
                    Message = toExpert,
                    Title = "稿件专审确认",
                    Recipient = auditingRecord.UserName
                });
        }
        public static AuditingRecord AppendExamineExpert(int articleId, string expert, DateTime finishDate)
        {
            string userName = HttpContext.Current.User.Identity.Name;
            var user = new User().Find(userName);
            var expertEntity = new User().Find(expert);
            if (String.IsNullOrEmpty(userName) || user == null || expertEntity == null)
            {
                return null;
            }

            var article = new Article().Find(articleId.ToString());
            if (article == null)
            {
                return null;
            }
            var meeting = new Meeting().Find(c => c.Id == article.Conference_Id);
            if (meeting == null || !(meeting.Admin.ToLower() == userName.ToLower() || user.SystemRole == UserRole.Admin))
            {
                return null;
            }

            var auditingRecord = new AuditingRecord()
            {
                CreateTime = DateTime.Now,
                Distributor = HttpContext.Current.User.Identity.Name,
                ExamineStatus = ExamineStatus.DaiShenHe,
                MeetingId = meeting.Id,
                ManuscriptId = article.Id,
                Step = article.Status == ArticleStatus.ZhuanShen ? ExamineStep.ZhuanShen : ExamineStep.ZhongShen,
                UserName = expert,
                ExamineFinishDate = finishDate
            }.PostAdd();
            //给专家发邮件
            string toExpert = EmailBuilder.BuildReviewNotityEmail(article.Id,
                                            auditingRecord.Id, expert, OrganizationType.Meeting, finishDate.ToString("yyyy-MM-dd"));
            if (!String.IsNullOrEmpty(toExpert))
            {
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                    new NormalNotifyEmail()
                    {
                        Recipient = expert,
                        Title = "专审邀请--《" + meeting.Name + "》",
                        Message = toExpert
                    });
            }
            //WorkPool.Append<ZhuanShenJobEmail>(WorkType.email_for_examinejobdistribution,
            //    new ZhuanShenJobEmail()
            //    {
            //        BackUrl = "/home/receivepostdata?token=" +
            //        EncodeByBase64.Encode(AesAlgorithm.Encrypt(new ExamineTokenModel()
            //        {
            //            ExamineId = auditingRecord.Id,
            //            ArticleId = article.Id,
            //            expertUsername = expert
            //        }.ToJson())),
            //        ExamineSheetPath = string.Empty,//HttpContext.Current.Server.MapPath(meeting.ExamineSheet),
            //        JournalName = meeting.Name,
            //        ManuscriptPath = HttpContext.Current.Server.MapPath(new Appendix().FindLast(c => c.RaletionId == article.Id && c.Type == (int)AttachmentType.Manuscript).Path),
            //        ExamineFinishDate = finishDate,
            //        Recipient = expert
            //    });
            return auditingRecord;
        }
        /// <summary>
        /// 验收
        /// </summary>
        /// <param name="articleId"></param>
        /// <param name="result">0:进入终审 1：要求专审修订 9：专审不通过</param>
        /// <param name="msg"></param>
        /// <returns> 0：失败 1：成功 2：重新分配专审 </returns>
        public static int AcceptanceExamine(int articleId, int result, string msg, params int[] records)
        {
            int reuslt = 0;
            var user = new User().Find(HttpContext.Current.User.Identity.Name);
            var article = new Article().Find(articleId.ToString());
            if (user == null || article == null)
            {
                reuslt= 0;
            }
            var meeting = new Meeting().Find(article.Conference_Id.ToString());
            if (meeting == null || !(meeting.Admin.ToLower() == HttpContext.Current.User.Identity.Name.ToLower() || user.SystemRole == UserRole.Admin))
            {
                reuslt= 0;
            }
            var attachment = new Appendix().FindLast(c => c.RaletionId == article.Id && c.Type == (int)AttachmentType.Manuscript);
            if (attachment == null)
            {
                reuslt= 0;
            }
            //进入终审
            if (result == 0)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhongShen,
                    ManuscriptId = article.Id,
                    Message = "终审中",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                new AuditingRecord()
                {
                    CreateTime = DateTime.Now,
                    Distributor = HttpContext.Current.User.Identity.Name,
                    ExamineStatus = ExamineStatus.DaiShenHe,
                    MeetingId = meeting.Id,
                    ManuscriptId = article.Id,
                    Message = "终审分配",
                    Step = ExamineStep.ZhongShen,
                    UserName = HttpContext.Current.User.Identity.Name
                }.PostAdd();

                article.Status = ArticleStatus.ZhongShen;
                article.PostModify();
                //给作者发邮件
                string toAuthor = EmailBuilder.BuildZhuanShenFinishEmail(article.Title);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件进入终审阶段",
                            Message = toAuthor
                        });
                }
                reuslt = 1;
            }
            else if (result == 1) //要求专审修订
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhuanShenXiuDing,
                    ManuscriptId = article.Id,
                    Message = "专审修订",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.ZhuanShenXiuDing;
                article.PostModify();

                string suggestion = BuildZhuanShenResultContent(article.Id,
                    "要求专审修订",
                    msg,
                    records);
                attachment.Suggestion = suggestion;
                attachment.PostModify();

                //给作者发邮件
                string toAuthor = EmailBuilder.BuildRevisionForAuthorEmail(article.Id, OrganizationType.Meeting, suggestion);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件需要修订",
                            Message = toAuthor
                        });
                }
                reuslt = 1;
            }
            else if (result == 2) //重新分配专审
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.ZhuanShenDaiFenPei,
                    ManuscriptId = article.Id,
                    Message = "重新分配专审",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.ZhuanShenDaiFenPei;
                article.PostModify();
                reuslt= 2;
            }
            else if (result == 9)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.Close,
                    ManuscriptId = article.Id,
                    Message = "专审不通过",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.Close;
                article.PostModify();

                string suggestion = BuildZhuanShenResultContent(article.Id,
                   "专审不通过",
                   msg,
                   records);
                attachment.Suggestion = suggestion;
                attachment.PostModify();

                //给作者发邮件
                string toAuthor = EmailBuilder.BuildZhuanShenRefuseEmail(
                    article.Title, suggestion);
                if (!String.IsNullOrEmpty(toAuthor))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Recipient = article.UserName,
                            Title = "您的稿件专审不通过",
                            Message = toAuthor//String.Format("您的稿件《{0}》专审不通过。<br/>{1}", article.Title, suggestion)
                        });
                }
                reuslt = 1;
            }


            var list = new AuditingRecord().FindAll(c => c.MeetingId == meeting.Id && c.ManuscriptId == articleId
                && c.Step == (int)ExamineStep.ZhuanShen && c.ExamineStatus == (int)ExamineStatus.DaiShenHe);
            if (list.Any())
            {
                foreach (var item in list)
                {
                    item.ExamineStatus = ExamineStatus.QuXiao;
                    item.PostModify();

                    //给专家发邮件
                    string toExpert = EmailBuilder.BuildCacnelExamineEmail(meeting.Name,
                          OrganizationType.Meeting, article.Title);
                    if (!String.IsNullOrEmpty(toExpert))
                    {
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                            new NormalNotifyEmail()
                            {
                                Recipient = item.UserName,
                                Title = "会议 \"" + meeting.Name + "\" 取消您对于稿件《" + article.Title + "》的审稿资格",
                                Message = toExpert
                            });
                    }
                }
            }
            return reuslt;
        }
        public static string BuildZhuanShenResultContent(int articleId, string examineResult, string suggestion, int[] examineId)
        {
            List<AuditingRecord> sheet = new List<AuditingRecord>();
            if (examineId != null && examineId.Any())
            {
                sheet = GetAllAuditingRecord(articleId, c => examineId.Contains(c.Id));
            }
            var article = new Article().Find(articleId.ToString());
            StringBuilder sb = new StringBuilder();
            sb.Append("<div style=\"width: 700px; height: auto;\">");
            if (article != null)
            {
                sb.Append("<fieldset>");
                sb.Append("<legend>专审验收结果</legend>");
                sb.Append("<div style=\"width: 650px; margin-left: auto; margin-right: auto;\">");
                sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%; border-bottom: 1px solid #eee;\">");
                sb.Append("<div style=\"width: 30%; float: left;\">稿件名：</div>");
                sb.Append(String.Format("<div>{0}</div>", article.Title));
                sb.Append("</div>");
                sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%; border-bottom: 1px solid #eee;\">");
                sb.Append("<div style=\"width: 30%; float: left;\">专审结论：</div>");
                sb.Append(String.Format("<div>{0}</div>", examineResult));
                sb.Append("</div>");
                sb.Append("<div style=\"display: block; height: auto; width: 100%;\">");
                sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">专审意见： </div>");
                sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                sb.Append(String.Format("<p>{0}</p>", suggestion));
                sb.Append("</div>");
                sb.Append("</div>");
                sb.Append("</div>");
                sb.Append("</div>");
                sb.Append("</fieldset>");
                sb.Append("<br/>");
            }
            if (sheet != null && sheet.Any())
            {
                char index = 'A';
                foreach (var item in sheet)
                {
                    sb.Append("<fieldset>");
                    sb.Append("<legend>" + index++ + "专家意见</legend>");
                    sb.Append("<div style=\"width: 650px; margin-left: auto; margin-right: auto;\">");
                    sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div style=\"width: 30%; float: left;\">1、稿件类型：</div>");
                    sb.Append(String.Format("<div>{0}</div>", item.ManuscriptType));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div>2、总体评价：</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div style=\"width: 20%; float: left;\">1）原创性：</div>");
                    sb.Append(String.Format("<div style=\"width: 20%; float: left;\">{0}</div>", item.Originality));
                    sb.Append("<div style=\"width: 20%; float: left;\">2）实用性：</div>");
                    sb.Append(String.Format("<div style=\"width: 20%; float: left;\">{0}</div>", item.Usefulness));
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div style=\"width: 20%; float: left;\">3）技术合理性：</div>");
                    sb.Append(String.Format("<div style=\"width: 20%; float: left;\">{0}</div>", item.Soundness));
                    sb.Append("<div style=\"width: 20%; float: left;\">4）语言描述：</div>");
                    sb.Append(String.Format("<div style=\"width: 20%; float: left;\">{0}</div>", item.LinguisticQuality));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div>3、稿件说明：</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">1)、稿件解决了什么问题？</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                    sb.Append(String.Format("<p>{0}</p>", item.Resolution));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">2)、主要领域作出的贡献？</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                    sb.Append(String.Format("<p>{0}</p>", item.Contribution));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("3)、在哪些方面确实缺乏原创？");
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                    sb.Append(String.Format("<p>{0}</p>", item.Originalless));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"width: 100%; border-bottom: 1px solid #ccc;\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">");
                    sb.Append("<div style=\"width: 30%; float: left;\">4、最终评审：</div>");
                    sb.Append(String.Format("<div>{0}</div>", item.SuggestStatus.Mapping()));
                    sb.Append("</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%\">");
                    sb.Append("<div style=\"display: block; height: 30px; line-height: 30px; width: 100%\">总体意见：</div>");
                    sb.Append("<div style=\"display: block; height: auto; width: 100%; word-break: break-all; text-indent: 20px;\">");
                    sb.Append(String.Format("<p>{0}</p>", item.Suggestion));
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("</div>");
                    sb.Append("</fieldset>");
                    sb.Append("<br/>");
                }
            }
            sb.Append("</div>");
            return sb.ToString();
        }
        public static void OverExamie(int articleId, string controlName)
        {
            var article = new Article().Find(articleId.ToString());
            if (article != null && article.Status == ArticleStatus.ChuBanYiJiaoFei)
            {
                var meeting = new Meeting().Find(article.Conference_Id.ToString());

                var file = HttpContext.Current.Request.Files[controlName];
                string appendixPath = string.Empty;
                string appendixName = string.Empty;
                string appendixCode = string.Empty;
                string format = string.Empty;
                string size = string.Empty;
                if (file != null && file.ContentLength > 0)
                {
                    appendixCode = new StreamFactory().BuildArticleAppendixCodeStreamNo(
                        article.Code, AttachmentStatus.DingGao, article.Id);
                    string basedir = "/content/meeting/" + meeting.Name + "/article/" + DateTime.Now.ToString("yyyy") + "/";
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                    }

                    var fileInfo = new FileInfo(file.FileName);
                    size = Math.Round(
                        decimal.Parse(file.ContentLength.ToString()) / 1024,
                        2).ToString() + " KB";
                    string extendName = fileInfo.Extension;
                    format = extendName.Replace(".", "").ToUpper();
                    appendixName = fileInfo.Name.Replace(extendName, "");

                    file.SaveAs(HttpContext.Current.Server.MapPath(basedir + appendixCode + extendName));
                    appendixPath = basedir + appendixCode + extendName;

                    //创建附件
                    var attachment = new Appendix()
                    {
                        AttachmentType = AttachmentType.Manuscript,
                        AppendixCode = appendixCode,
                        CreateTime = DateTime.Now,
                        FileName = appendixName,
                        Path = appendixPath,
                        Own = HttpContext.Current.User.Identity.Name,
                        RaletionId = article.Id,
                        AttachmentStatus = AttachmentStatus.DingGao,
                        Format = format,
                        Size = size
                    };
                    attachment.PostAdd();

                    new ArticleHistory() { 
                        CreateTime=DateTime.Now,
                        CurrentStatus= ArticleStatus.DaiChuBan,
                        ManuscriptId=article.Id,
                        Message="定稿",
                        Operator=HttpContext.Current.User.Identity.Name,
                        PreStatus=article.Status
                    }.PostAdd();

                    article.Status = ArticleStatus.DaiChuBan;
                    article.PostModify();
                    if (attachment == null)
                    {
                        LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "保存定稿附件失败，请手工处理" + Environment.NewLine + attachment.ToJson());
                    }
                }
            }
        }
        #endregion

        #region 人员管理
        public static List<Organization> GetAllLeaguer(int meetingId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.Organization
                            join u in ctx.User
                             on c.UserName equals u.UserName
                            join e in ctx.Expert
                             on c.UserName equals e.UserName
                            where c.OrgId == meetingId && c.OrgType == (int)OrganizationType.Meeting && c.ApplyStatus == 1 && c.Status == (int)JournalStatus.Counsellor
                            orderby c.Id
                            select new { c, u, e }
                           )
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c =>
                               new Organization().Set(c.c)
                                .LoadUser(
                                    new User().Set(c.u),
                                    new Expert().Set(c.e)))
                           .ToList();
                return list;
            }
        }
        public static int GetAllLeaguerForPage(int meeting)
        {
            using (Context ctx = new Context())
            {
                return ctx.Organization.Count(c => c.OrgId == meeting && c.OrgType == (int)OrganizationType.Meeting);
            }
        }
        /// <summary>
        /// 移除管委会成员
        /// </summary>
        /// <param name="meetingId"></param>
        /// <param name="userName"></param>
        public static void CancelEditorial(int meetingId, string userName)
        {
            var item = new Organization().Find(c => c.OrgId == meetingId && c.OrgType == (int)OrganizationType.Meeting && c.UserName == userName && c.Status == (int)JournalStatus.Counsellor);
            if (item != null)
            {
                if (item.PostDelete() == null)
                {
                    LogHelper.Write(CommonLogger.Journal, LogLevel.Error, "会议id:" + meetingId + " 删除用户：" + userName + " 为管委会成员失败。请技术处理");
                }
            }
        }
        public static List<Organization> GetAllPendingMember(int meetingId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = (from c in ctx.Organization
                            where c.OrgId == meetingId && c.OrgType == (int)OrganizationType.Meeting && c.ApplyStatus != 1
                            orderby c.Id
                            select new { c }
                           )
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c =>
                               new Organization().Set(c.c))
                           .ToList();
                return list;
            }
        }
        /// <summary>
        /// 重发专家邀请邮件
        /// </summary>
        /// <param name="account"></param>
        public static void ReMailToInviteExpert(string account, int meetingId)
        {
            var meetingEntity = new Meeting().Find(meetingId.ToString());
            var invite = new Organization().Find(c => c.OrgId == meetingId && c.OrgType == (int)OrganizationType.Meeting && c.UserName == account && c.Status == 2 && c.ApplyStatus == 0);
            if (invite != null)
            {
                string toExpert = EmailBuilder.BuildInviteForExpertEmail(TaskType.MeetingToExpert,
                        account, OrganizationType.Meeting, meetingEntity.Name, meetingEntity.Id,
                        invite.Id);
                if (!String.IsNullOrEmpty(toExpert))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                      new NormalNotifyEmail()
                      {
                          Recipient = account,
                          Title = meetingEntity.Name + " 邀请您加入编委会",
                          Message = toExpert
                      });
                }
                //WorkPool.Append<InviteForJournalNotityEmail>(WorkType.email_for_invitereviser_notity,
                // new InviteForJournalNotityEmail()
                // {
                //     Type = (int)TaskType.MeetingToExpert,
                //     JournalId = meetingId,  
                //     JournalLeaguerId = invite.Id,
                //     JournalName = meetingEntity.Name,
                //     Recipient = account
                // });
            }
        }
        /// <summary>
        /// 邀请站外专家
        /// </summary>
        /// <param name="expertAccount"></param>
        /// <param name="meeting"></parasm>
        /// <returns></returns>
        public static int MailToInviteForExpert(string expertAccount, int meeting)
        {
            var user = new User().Find(expertAccount);
            if (user != null)
            {
                if (user.IsActivate)
                {
                    if (user.SystemRole == UserRole.Expert)
                    {
                        return 2;
                    }
                    else
                    {
                        return 3;
                    }
                }
            }
            else
            {
                //占用账号名额
                new User()
                {
                    Area = AreaCode.BeiJing,
                    Birthday = DateTime.Parse("1970-01-01"),
                    Email = expertAccount,
                    Gender = Gender.Male,
                    IsActivate = false,
                    IsRefuse = false,
                    Location = Location.BeiJing,
                    NickName = "专家",
                    Password = AesAlgorithm.Encrypt("123456"),
                    SystemRole = UserRole.Expert,
                    RcdDate = DateTime.Now,
                    UserName = expertAccount
                }.PostAdd();
            }
            Organization item = new Organization().Find(c => c.OrgId == meeting && c.OrgType == (int)OrganizationType.Meeting && c.UserName == expertAccount && c.Status == 2 && c.ApplyStatus == 0);
            if (item == null)
            {
                item = new Organization()
                {
                    ApplyStatus = 0,
                    JoinDate = DateTime.Now,
                    OrgId = meeting,
                    OrgType = OrganizationType.Meeting,
                    Status = JournalStatus.Counsellor,
                    UserName = expertAccount
                }.PostAdd();
            }
            var meetingEntity = new Meeting().Find(meeting.ToString());
            string toExpert = EmailBuilder.BuildInviteForExpertEmail(TaskType.NoticeToExpert,
                expertAccount, OrganizationType.Meeting, meetingEntity.Name, meetingEntity.Id, item.Id);
            if (!String.IsNullOrEmpty(toExpert))
            {
                //toExpert = EmailBuilder.BuildInviteForExpertEmail(TaskType.NoticeToExpert,
                //    expertAccount, OrganizationType.Meeting, meetingEntity.Name, meetingEntity.Id, item.Id);
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                   new NormalNotifyEmail()
                   {
                       Recipient = expertAccount,
                       Title = meetingEntity.Name + " 邀请您加入编委会",
                       Message = toExpert
                   });
            }
            //WorkPool.Append<InviteForJournalNotityEmail>(WorkType.email_for_inviteexpert_notity,
            //    new InviteForJournalNotityEmail()
            //    {
            //        Type = (int)TaskType.MeetingToExpert,
            //        JournalId = meeting,
            //        JournalLeaguerId = item.Id,
            //        JournalName = meetingEntity.Name,
            //        Recipient = expertAccount
            //    });
            return 1;
        }
        /// <summary>
        /// 邀请站内专家
        /// </summary>
        /// <param name="expertAccount"></param>
        /// <param name="meeting"></param>
        /// <returns></returns>
        public static bool DoInviteForExpert(string expertAccount, int meeting)
        {
            var item = new Organization().Find(c => c.OrgId == meeting && c.OrgType == (int)OrganizationType.Meeting && c.UserName == expertAccount && c.Status == (int)JournalStatus.Counsellor);
            //如果已经存在 且已经通过确认
            if (item != null && item.ApplyStatus == 1)
            {
                return false;
            }
            //如果不存在
            else if (item == null)
            {
                item = new Organization()
                {
                    ApplyStatus = 0,
                    JoinDate = DateTime.Now,
                    OrgId = meeting,
                    OrgType = OrganizationType.Meeting,
                    Status = JournalStatus.Counsellor,
                    UserName = expertAccount
                }.PostAdd();
            }
                //如果还未处理。重发邮件
            if (item.ApplyStatus == 0)
            {
                var meetingEntity = new Meeting().Find(meeting.ToString());
                string toExpert = EmailBuilder.BuildInviteForExpertEmail(TaskType.MeetingToExpert,
                       expertAccount, OrganizationType.Meeting, meetingEntity.Name, meetingEntity.Id,
                       item.Id);
                if (!String.IsNullOrEmpty(toExpert))
                {
                    WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                      new NormalNotifyEmail()
                      {
                          Recipient = expertAccount,
                          Title = meetingEntity.Name + " 邀请您加入编委会",
                          Message = toExpert
                      });
                }
                //WorkPool.Append<InviteForJournalNotityEmail>(WorkType.email_for_inviteexpert_notity,
                //    new InviteForJournalNotityEmail()
                //    {
                //        Type = (int)TaskType.MeetingToExpert,
                //        JournalId = meeting,
                //        JournalLeaguerId = item.Id,
                //        JournalName = meetingEntity.Name,
                //        Recipient = expertAccount
                //    });
            }
            return true;
        }
        public static void RefuseInviteExpert(int leagerid, int meetingId, string expertAccount)
        {
            var item = new Organization().Find(c => c.Id == leagerid && c.OrgType == (int)OrganizationType.Meeting && c.OrgId == meetingId && c.UserName == expertAccount
                && c.Status == (int)JournalStatus.Counsellor && c.ApplyStatus == 0);
            if (item != null)
            {
                item.ApplyStatus = 2;
                item.Message = "他（她）拒绝了您的邀请";
                item.PostModify();

                //删除临时占用账号
                var user = new User().Find(expertAccount);
                if (!user.IsActivate)
                {
                    user.PostDelete();
                }
            }
        }
        #endregion

        public static ConferenceMapping GetMeetingMapping(string requestDomain)
        {
            var dict = iCache.Get("MeetingBiz.GetMeetingMapping", () => { return new ConferenceMapping().FindAll(); }, 6000);
            if (dict != null && dict.Any())
            {
                var item = dict.Find(c => c.Host.ToLower() == requestDomain.ToLower());
                return item;
            }
            return null;
        }
    }
}
